<?php declare(strict_types=1);

namespace App\Exception\Handler;

use const APP_DEBUG;
use function get_class;
use ReflectionException;
use function sprintf;
use Swoft\Bean\Exception\ContainerException;
use Swoft\Error\Annotation\Mapping\ExceptionHandler;
use Swoft\Http\Message\Response;
use Swoft\Http\Server\Exception\Handler\AbstractHttpErrorHandler;
use Swoft\Http\Server\Exception\NotFoundRouteException;
use Swoft\Log\Helper\CLog;
use Throwable;
use App\Common\Http\Response as Rp;

/**
 * Class HttpExceptionHandler
 *
 * @ExceptionHandler(\Throwable::class)
 */
class HttpExceptionHandler extends AbstractHttpErrorHandler
{
    /**
     * @param Throwable $e
     * @param Response   $response
     *
     * @return Response
     */
    public function handle(Throwable $e, Response $response): Response
    {
        // Log
        CLog::error($e->getMessage());

        if ($e instanceof NotFoundRouteException) {
            return $response->withData(Rp::fail("路由找不到"));
        }

        // Debug is true
        return $response->withData(Rp::fail(Rp::TEXT_SYSTEM_ERROR));
    }
}
